package com.project.server;

import com.project.service.*;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class ServerThread implements Runnable{

    private static final String header = "HTTP/1.1 200 OK\r\n" +
            "Content-Type: text/html;charSet=utf-8\r\n" +
            "\r\n";

    private Socket socket;
    public ServerThread(Socket socket){
        this.socket = socket;

        //传入本类，开启线程
        new Thread(this).start();
    }
    @Override
    public void run() {

        try {
            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();
            //把输入流封装到request中
            Request request = new Request(in);

            //把响应信息封装到response中
            Response response = new Response(out);

            //服务器想客户端发送的信息。（这里的常量是让谷歌浏览器能解析）
            out.write(header.getBytes());
//            out.write("欢迎访问".getBytes());

            //得到路径
            String url = request.getUrl();

           //用ServletFactory工厂调方法，传入路径得到业务对象servlet，
            //Servlet多态
            Servlet servlet = ServletFactory.getServlet(url);
            if (servlet != null){ //该对象存在则表示请求的是业务
                servlet.service(request,response);
            }
            else {//对象为null，表示请求的是文件直接响应即可
                response.sendFile(url);
            }
//            if ("land".equals(url)){//客户端请求的是登录业务
//                LoginService login = new LoginService();
//                login.service(request,response);
//            }
//            else if ("findAll".equals(url)){
//                FindAllService findAll = new FindAllService();
//                findAll.service(request,response);
//            }
//            else if("add".equals(url)){
//                AddService add = new AddService();
//                add.service(request,response);
//            }
//            else if ("del".equals(url)){
//                DelService del = new DelService();
//                del.service(request,response);
//            }
//            else if ("findById".equals(url)){
//                FindByIdService find = new FindByIdService();
//                find.service(request,response);
//            } else if ("update".equals(url)){
//                UpdateService update = new UpdateService();
//                update.service(request,response);
//            }else if ("cutAll".equals(url)){
//                CutAllService cutAllService = new CutAllService();
//                cutAllService.service(request,response);
//            }
//            else {//请求的是文件
//                //传入想要访问的路径
//                response.sendFile(url);
//            }
            //刷新流
            out.flush();

            //关闭连接
            out.close();
            in.close();
            socket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
